# -*- coding: utf-8 -*-
### BEGIN LICENSE
# This file is in the public domain
### END LICENSE

import gtk

import xml.etree.ElementTree as ET

from wau.helpers import get_builder

import re, os, logging

import gettext
from gettext import gettext as _
gettext.textdomain('wau')

from wau import PreferencesWauDialog, addons

class PublishaddonDialog(gtk.Dialog):
    __gtype_name__ = "PublishaddonDialog"

    def __new__(cls):
        """Special static method that's automatically called by Python when 
        constructing a new instance of this class.
        
        Returns a fully instantiated PublishaddonDialog object.
        """
        builder = get_builder('PublishaddonDialog')
        new_object = builder.get_object('publishaddon_dialog')
        new_object.finish_initializing(builder)
        return new_object

    def finish_initializing(self, builder):
        """Called when we're finished initializing.

        finish_initalizing should be called after parsing the ui definition
        and creating a PublishaddonDialog object with it in order to
        finish initializing the start of the new PublishaddonDialog
        instance.
        """
        # Get a reference to the builder and set up the signals.
        self.builder = builder
        self.builder.connect_signals(self)
        
        dlg = PreferencesWauDialog.PreferencesWauDialog()
        self.config = dlg.get_preferences()

        self.get_text = lambda x: self.builder.get_object(x).get_text()

        settings = [
            ('addonFolder', 'file'),
            ('addonName', 'entry'),
            ('addonAuthor', 'entry'),
            ('addonVersion', 'entry'),
            ('addonUpdateURL', 'entry'),
            ('outputFolder', 'file'),
            ('addonHomepage', 'entry'),
            ('addonEmail', 'entry'),
            ('addonChangelog', 'entry'),
            ('addonDescription', 'entry'),
        ]

        self.store = PreferencesWauDialog.DataStorer(settings, self.config, builder, "myaddon")
        
        self.at = addons.AddonTools()
        
        self.store.load_preferences()

    def create_client_xml(self, filename, xmlurl):
        root = ET.Element("addon")
        
        update = ET.SubElement(root, "update")
        ET.SubElement(update, "url").text = xmlurl
        
        info = ET.SubElement(root, "information")
        ET.SubElement(info, "author").text = self.get_text("addonAuthor")
        ET.SubElement(info, "name").text = self.get_text('addonName')
        ET.SubElement(info, "homepage").text = self.get_text('addonHomepage')
        ET.SubElement(info, "email").text = self.get_text('addonEmail')
        ET.SubElement(info, "description").text = self.get_text('addonDescription')
        
        ver = ET.SubElement(root, "version")
        ET.SubElement(ver, "string").text = self.get_text("addonVersion")
        ET.SubElement(ver, "number").text = self.store.get("version")
        
        tree = ET.ElementTree(root)
        tree.write(filename)

    def create_server_xml(self, filename, fileurl):
        
        root = ET.Element("addon")
        
        information = ET.SubElement(root, "information")
        ET.SubElement(information, "name").text = self.get_text("addonName")
        
        version = ET.SubElement(root, "version")
        ET.SubElement(version, "number").text = self.store.get("version")
        ET.SubElement(version, "changelog").text = self.get_text("addonChangelog")
        ET.SubElement(version, "string").text = self.get_text("addonVersion")
        
        download = ET.SubElement(root, "download")
        ET.SubElement(download, "url").text = fileurl
        
        tree = ET.ElementTree(root)
        tree.write(filename)

    def make_release(self, widget, data=None):
        self.store.save_preferences()
        
        if not self.store.get("version"):
            self.store.put("version", 0)
            
        v = int(self.store.get("version")) + 1
        self.store.put("version", v)
        
        addon_name = self.store.get("addonName")
        filter = lambda data: "".join([x for x in data if x.isalpha() or x.isdigit() or x in "-_"])
        filename = filter(addon_name)
        version = filter(self.store.get("addonVersion"))
        
        outpath = self.store.get("outputFolder")
        zfn = filename+"-"+version+".zip"
        zf = os.path.join(outpath, zfn)
        
        addonpath = self.store.get("addonFolder")
        
        updateurl = self.get_text("addonUpdateURL").strip().strip("/")
        
        serverxml = updateurl + "/" + "server.xml"
        updatefile = updateurl + "/" + zfn
        
        self.create_client_xml(os.path.join(addonpath, "update.xml"), serverxml)
        self.create_server_xml(os.path.join(outpath, "server.xml"), updatefile)
        
        self.at.enzip(addonpath, zf)

    def refresh_from_toc(self, widget, data=None):
        folder = self.builder.get_object("addonFolder").get_filename()
        se.get_toc_data(folder, True)

    def get_toc_data(self, folder, override=False):
        files = os.listdir(folder)
        tocfile = None
        for x in files:
            if len(x) > 3 and x[-3:] == "toc":
                tocfile = x
                break
        
        if not tocfile:
            logging.debug(u"No tocfile for %s" % folder)
            return False
        
        logging.debug("Tocfile : %s" % tocfile)
        
        translations = [
            ("Title", "addonName"),
            ("Author", "addonAuthor"),
            ("Notes", "addonDescription"),
            ("Version", "addonVersion"), 
            ("X-Website", "addonHomepage"),
        ]

        f = open(os.path.join(folder, tocfile))
        data = f.read()
        f.close()
        
        for key, gname in translations:
            obj = self.builder.get_object(gname)
            if override or not obj.get_text():
                skey = "(?m)^## %s: (.+?)$" % key
                
                logging.debug(u"Regex key : %s" % skey)

                hit = re.search(skey, data)
                if hit:
                    logging.debug(u"Hit found : %s" % hit.group(1))
                    obj.set_text(hit.group(1))
                else:
                    logging.debug("No match found")
        
    def on_file_set(self, widget, data=None):
        self.get_toc_data(widget.get_filename())

    def ok(self, widget, data=None):
        """The user has elected to save the changes.

        Called before the dialog returns gtk.RESONSE_OK from run().
        """
        self.store.save_preferences()
        pass

if __name__ == "__main__":
    dialog = PublishaddonDialog()
    dialog.show()
    gtk.main()
